//
//  XGEmojiManager.swift
//  Emoji
//
//  Created by monkey on 2020/3/2.
//  Copyright © 2020 itcast. All rights reserved.
//

import HandyJSON
import YYText

struct XGEmojiModel: HandyJSON
{
    var id: String?
    var name: String?
    var png: String?
}

class XGEmojiManager
{
    public static let shared = XGEmojiManager()
        
    /// 将带表情名称的字符串转换富文本
    /// - Parameters:
    ///   - contnet: 字符串
    ///   - fontSize: 字体大小
    ///   - textColor: 字体颜色
    func convertToAttributeString(contnet: String, fontSize: CGFloat = 15, textColor: UIColor = UIColor.darkGray) -> NSAttributedString
    {
        let pattern = "\\[.*?\\]"
        let font = UIFont.systemFont(ofSize: fontSize)
        let attributeStrM = NSMutableAttributedString(string: contnet, attributes: [.font: font,.foregroundColor: textColor])
        // 正则匹配表情
        let regularExpression = try? NSRegularExpression(pattern: pattern, options: [])
        guard let results = regularExpression?.matches(in: contnet, options: [], range: NSRange(location: 0, length: contnet.count)) else {
            return attributeStrM
        }

        // 将表情字符串替换为图片
        for result in results.reversed() {
            let emojiName = (contnet as NSString).substring(with: result.range)
            let image = self.convertToImage(emojiName)
            let imageWidth = ceil(font.lineHeight) + 1
            let imageAttachmentString = NSAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFill, attachmentSize: CGSize(width: imageWidth, height: imageWidth), alignTo: font, alignment: .center)
            attributeStrM.replaceCharacters(in: result.range, with: imageAttachmentString)
        }
        
        attributeStrM.yy_lineSpacing = 5
        return attributeStrM
    }
    
    /// 将表情名称转为图片
    /// - Parameter name: 表情名称
    func convertToImage(_ name: String) -> UIImage?
    {
        if let name = emojis?.filter({ return $0.name == name }).first?.png {
            let scale = UIScreen.main.scale == 2 ? "@2x" : "@3x"
            let imageName = name + scale
            guard let path = Bundle.main.path(forResource: imageName, ofType: "png") else {
                return nil
            }
            return UIImage(contentsOfFile: path)
        }
        
        return nil
    }
    
    private var emojis: [XGEmojiModel]?
    private init()
    {
        let path = Bundle.main.path(forResource: "emojis.plist", ofType: nil)!
        let arr = NSArray(contentsOfFile: path) as? [[String: Any]]
        emojis = arr?.compactMap({ return XGEmojiModel.deserialize(from: $0)})
    }
}
